# HUB 插件 - UI模块
# 实现UI相关功能

require 'sketchup.rb'

module HUB
  module UIHelper
    
    # 显示进度条
    def self.show_progress_bar(title, max_value)
      begin
        puts "HUB-调试: 尝试创建进度条 #{title}"
        
        # 判断是否支持HtmlDialog
        if defined?(UI::HtmlDialog)
          begin
            progress_bar = ProgressBar.new(title, max_value)
            progress_bar.show
            puts "HUB-调试: 成功创建并显示HTML进度条"
            return progress_bar
          rescue => e
            puts "HUB-调试: HTML进度条创建失败: #{e.message}"
            puts "HUB-调试: #{e.backtrace.join("\n")}"
            puts "HUB-调试: 尝试使用传统进度条作为备选"
            
            # 如果HTML进度条失败，使用传统进度条
            progress_bar = LegacyProgressBar.new(title, max_value)
            progress_bar.show
            return progress_bar
          end
        else
          puts "HUB-调试: 当前SketchUp版本不支持HtmlDialog，使用传统进度条"
          progress_bar = LegacyProgressBar.new(title, max_value)
          progress_bar.show
          return progress_bar
        end
      rescue => e
        puts "HUB-调试: 进度条创建过程中发生严重错误: #{e.message}"
        puts "HUB-调试: #{e.backtrace.join("\n")}"
        
        # 创建一个不抛出异常的空进度条，以防止整个上传过程崩溃
        return NullProgressBar.new(title, max_value)
      end
    end
    
    # 显示输入对话框
    def self.show_input_dialog(title, prompt, default_value = "")
      input = UI.inputbox([prompt], [default_value], title)
      return input ? input[0] : nil
    end
    
    # 显示消息框
    def self.show_message(message, title = "HUB 插件")
      UI.messagebox(message, MB_OK, title)
    end
    
    # 显示错误消息
    def self.show_error(message, title = "错误")
      UI.messagebox(message, MB_OK, title)
    end
    
    # 显示确认对话框
    def self.show_confirm(message, title = "确认")
      result = UI.messagebox(message, MB_YESNO, title)
      return result == IDYES
    end
    
    # 显示状态栏消息
    def self.show_status_text(message)
      Sketchup.status_text = message
    end
    
    # 空进度条类 - 用于在出现错误时提供一个不会崩溃的实现
    class NullProgressBar
      def initialize(title, max_value)
        @title = title
        @max_value = max_value
        puts "HUB-调试: 创建空进度条 - #{title}"
      end
      
      def show
        puts "HUB-调试: 显示空进度条"
        Sketchup.status_text = "#{@title}..."
      end
      
      def update(value, message = nil)
        percent = (value.to_f / @max_value * 100).to_i
        Sketchup.status_text = "#{message || @title}: #{percent}%"
      end
      
      def close
        Sketchup.status_text = ""
      end
    end
    
    # 原始进度条实现（保留作为备份）
    class LegacyProgressBar
      def initialize(title, max_value)
        @title = title
        @max_value = max_value.to_f
        @current_value = 0
        @started_time = nil
        @status_text = nil
        @visible = false
        puts "HUB-调试: 创建传统进度条 - #{title}"
      end
      
      # 显示进度条
      def show
        @started_time = Time.now
        @visible = true
        
        # 设置初始状态文本
        @status_text = "#{@title}..."
        
        # 更新状态栏
        Sketchup.status_text = @status_text
        
        # 在左上角显示"进度"文本
        Sketchup.set_status_text("进度", SB_PROMPT)
        
        # 初始化显示
        update(0, "初始化...")
        puts "HUB-调试: 传统进度条已显示"
      end
      
      # 更新进度条
      def update(value, message = nil)
        return unless @visible
        
        # 计算百分比
        @current_value = value.to_f
        percent = (@current_value / @max_value * 100).to_i
        percent = 100 if percent > 100
        percent = 0 if percent < 0
        
        # 生成状态文本
        @status_text = message || "#{@title}: #{percent}%"
        
        # 计算已用时间
        elapsed_time = Time.now - @started_time
        elapsed_str = format_time(elapsed_time)
        
        # 更新状态栏
        Sketchup.status_text = "#{@status_text} (#{elapsed_str})"
        
        # 显示百分比在VCB区域
        Sketchup.set_status_text("#{percent}%", SB_VCB_VALUE)
        
        # 刷新界面 - SketchUp 2024不支持此方法，移除以避免错误
        # Sketchup.active_model.invalidate_view
      end
      
      # 关闭进度条
      def close
        @visible = false
        
        # 重置状态栏
        Sketchup.status_text = ""
        Sketchup.set_status_text("", SB_VCB_VALUE)
        
        # 刷新界面 - SketchUp 2024不支持此方法，移除以避免错误
        # Sketchup.active_model.invalidate_view
        puts "HUB-调试: 传统进度条已关闭"
      end
      
      private
      
      # 格式化时间
      def format_time(seconds)
        seconds = seconds.to_i
        if seconds < 60
          return "#{seconds}秒"
        elsif seconds < 3600
          minutes = seconds / 60
          seconds = seconds % 60
          return "#{minutes}分#{seconds}秒"
        else
          hours = seconds / 3600
          minutes = (seconds % 3600) / 60
          return "#{hours}时#{minutes}分"
        end
      end
    end
    
    # HTML进度条类 - 使用HtmlDialog显示现代化的进度条
    class ProgressBar
      def initialize(title, max_value)
        @title = title
        @max_value = max_value.to_f
        @current_value = 0
        @last_value = 0
        @last_update_time = Time.now
        @started_time = Time.now
        @status_text = nil
        @visible = false
        @dialog = nil
        @speed = 0 # 上传速度 (单位：%/秒)
        
        puts "HUB-调试: 开始创建HTML进度条 - #{title}"
        
        # 创建对话框
        create_dialog
      end
      
      # 创建HTML对话框
      def create_dialog
        puts "HUB-调试: 创建HTML对话框"
        
        begin
          # 获取屏幕尺寸，以便定位对话框在左上角
          screen_width = Sketchup.active_model.active_view.vpwidth rescue 1200
          screen_height = Sketchup.active_model.active_view.vpheight rescue 800
          puts "HUB-调试: 屏幕尺寸 #{screen_width}x#{screen_height}"

          # 计算对话框位置（左上角，预留20像素的边距）
          dialog_left = 20
          dialog_top = 20
          
          # 创建对话框实例
          puts "HUB-调试: 初始化HtmlDialog对象"
          @dialog = UI::HtmlDialog.new({
            :dialog_title => "#{@title}",
            :preferences_key => "HUB_ProgressBar",
            :scrollable => false,
            :resizable => false,
            :width => 360,
            :height => 150,
            :left => dialog_left,
            :top => dialog_top,
            :style => UI::HtmlDialog::STYLE_DIALOG
          })
          
          puts "HUB-调试: HtmlDialog对象创建成功"
          
          # 设置HTML内容
          html_content = <<~HTML
            <!DOCTYPE html>
            <html>
            <head>
              <meta charset="UTF-8">
              <title>上传进度</title>
              <style>
                body {
                  font-family: 'Microsoft YaHei', Arial, sans-serif;
                  margin: 0;
                  padding: 15px;
                  background-color: #f5f5f5;
                  overflow: hidden;
                  user-select: none;
                }
                .progress-container {
                  margin-bottom: 10px;
                }
                .progress-bar {
                  height: 20px;
                  background-color: #e0e0e0;
                  border-radius: 10px;
                  overflow: hidden;
                  position: relative;
                  box-shadow: inset 0 1px 3px rgba(0,0,0,0.2);
                }
                .progress-fill {
                  height: 100%;
                  background-color: #4CAF50;
                  background-image: linear-gradient(45deg, 
                                    rgba(255,255,255,.15) 25%, transparent 25%, 
                                    transparent 50%, rgba(255,255,255,.15) 50%, 
                                    rgba(255,255,255,.15) 75%, transparent 75%, 
                                    transparent);
                  background-size: 20px 20px;
                  transition: width 0.3s ease;
                  width: 0%;
                  animation: progress-animation 1s linear infinite;
                }
                @keyframes progress-animation {
                  0% {
                    background-position: 0 0;
                  }
                  100% {
                    background-position: 40px 0;
                  }
                }
                .progress-status {
                  display: flex;
                  justify-content: space-between;
                  margin-top: 5px;
                  font-size: 14px;
                }
                .message {
                  font-weight: bold;
                  margin-bottom: 10px;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                }
                .info-container {
                  display: flex;
                  justify-content: space-between;
                  font-size: 12px;
                  color: #666;
                  margin-top: 5px;
                }
                .elapsed-time {
                  text-align: right;
                }
                .speed {
                  text-align: left;
                }
                /* 添加漂亮的标题栏 */
                .title-bar {
                  background: linear-gradient(to right, #2b5876, #4e4376);
                  color: white;
                  padding: 8px 15px;
                  font-weight: bold;
                  margin: -15px -15px 15px -15px;
                  border-radius: 3px 3px 0 0;
                  display: flex;
                  align-items: center;
                }
                .title-icon {
                  margin-right: 8px;
                  font-size: 16px;
                }
              </style>
            </head>
            <body>
              <div class="title-bar">
                <span class="title-icon">📤</span>
                <span>HUB 模型上传</span>
              </div>
              
              <div class="message" id="message">初始化...</div>
              <div class="progress-container">
                <div class="progress-bar">
                  <div class="progress-fill" id="progressFill"></div>
                </div>
                <div class="progress-status">
                  <div id="percentText">0%</div>
                  <div class="info-container">
                    <div class="speed" id="speedText">--</div>
                    <div class="elapsed-time" id="elapsedTime">0秒</div>
                  </div>
                </div>
              </div>

              <script>
                // 更新进度条
                function updateProgress(percent, message, elapsedTime, speed) {
                  document.getElementById('progressFill').style.width = percent + '%';
                  document.getElementById('percentText').textContent = percent + '%';
                  document.getElementById('message').textContent = message || '';
                  document.getElementById('elapsedTime').textContent = elapsedTime || '';
                  
                  // 如果提供了速度信息，则显示
                  if (speed && speed > 0) {
                    document.getElementById('speedText').textContent = '速度: ' + speed.toFixed(1) + '%/秒';
                    
                    // 调整动画速度以反映实际上传速度
                    var animation = speed * 0.05; // 根据速度调整动画速度
                    animation = Math.max(0.5, Math.min(animation, 3)); // 限制在合理范围内
                    document.getElementById('progressFill').style.animationDuration = animation + 's';
                  }
                }
                
                // 初始设置
                updateProgress(0, '#{@title}', '');
                
                // 使窗口始终保持在最前方
                window.onload = function() {
                  window.focus();
                  console.log("窗口已加载并获取焦点");
                };
                
                // 告诉Ruby脚本窗口已加载完成
                try {
                  window.location.href = 'skp:on_loaded@';
                } catch(e) {
                  console.log("无法调用skp回调: " + e);
                }
              </script>
            </body>
            </html>
          HTML
          
          puts "HUB-调试: 设置HTML内容"
          @dialog.set_html(html_content)
          
          # 添加回调函数
          puts "HUB-调试: 添加回调函数"
          @dialog.add_action_callback("close") { |action_context| close }
          @dialog.add_action_callback("on_loaded") { |action_context| puts "HUB-调试: HTML内容已加载完成" }
          
          # 设置对话框总是在最前面
          @dialog.set_on_closed { 
            puts "HUB-调试: 对话框已关闭"
            @visible = false
            @dialog = nil 
          }
          
          puts "HUB-调试: HTML对话框创建完成"
        rescue => e
          puts "HUB-调试: 创建HTML对话框时出错: #{e.message}"
          puts "HUB-调试: #{e.backtrace.join("\n")}"
          raise e # 重新抛出异常，让外层处理
        end
      end
      
      # 显示进度条
      def show
        return if @visible
        
        puts "HUB-调试: 尝试显示HTML进度条"
        begin
          if @dialog.nil?
            puts "HUB-调试: 对话框为空，尝试重新创建"
            create_dialog
          end
          
          @started_time = Time.now
          @last_update_time = Time.now
          @last_value = 0
          @visible = true
          
          puts "HUB-调试: 调用dialog.show方法"
          @dialog.show
          
          # 将对话框设置为始终在顶部显示
          puts "HUB-调试: 将对话框置于前台"
          @dialog.bring_to_front
          
          update(0, "初始化...")
          
          # 同步更新状态栏
          Sketchup.status_text = "#{@title}..."
          puts "HUB-调试: HTML进度条显示成功"
        rescue => e
          puts "HUB-调试: 显示HTML进度条时出错: #{e.message}"
          puts "HUB-调试: #{e.backtrace.join("\n")}"
          @visible = false
          raise e # 重新抛出异常，让外层处理
        end
      end
      
      # 更新进度条
      def update(value, message = nil)
        return unless @visible
        
        # 计算百分比
        current_time = Time.now
        @current_value = value.to_f
        percent = (@current_value / @max_value * 100).to_i
        percent = 100 if percent > 100
        percent = 0 if percent < 0
        
        # 计算速度 (只有当前值与上次不同时才计算)
        if @current_value != @last_value && current_time != @last_update_time
          time_diff = current_time - @last_update_time
          value_diff = @current_value - @last_value
          
          # 计算每秒百分比变化
          if time_diff > 0
            percent_diff = (value_diff / @max_value * 100)
            @speed = percent_diff / time_diff
          end
          
          # 更新最后值和时间
          @last_value = @current_value
          @last_update_time = current_time
        end
        
        # 生成状态文本
        @status_text = message || "#{@title}: #{percent}%"
        
        # 计算已用时间
        elapsed_time = current_time - @started_time
        elapsed_str = format_time(elapsed_time)
        
        # 更新HTML进度条
        begin
          update_html_progress(percent, @status_text, elapsed_str, @speed)
        rescue => e
          puts "HUB-调试: 更新HTML进度条时出错: #{e.message}"
        end
        
        # 同步更新状态栏（备用显示）
        Sketchup.status_text = "#{@status_text} (#{elapsed_str})"
      end
      
      # 更新HTML进度条
      def update_html_progress(percent, message, elapsed_time, speed = nil)
        if @dialog && @visible
          begin
            js_command = "updateProgress(#{percent}, '#{escape_js(message)}', '#{escape_js(elapsed_time)}', #{speed || 'null'})"
            @dialog.execute_script(js_command)
          rescue => e
            puts "HUB-调试: 执行JavaScript时出错: #{e.message}"
          end
        end
      end
      
      # 关闭进度条
      def close
        if @dialog && @visible
          puts "HUB-调试: 关闭HTML进度条"
          begin
            @visible = false
            @dialog.close
            @dialog = nil
            
            # 重置状态栏
            Sketchup.status_text = ""
            puts "HUB-调试: HTML进度条已关闭"
          rescue => e
            puts "HUB-调试: 关闭HTML进度条时出错: #{e.message}"
          end
        end
      end
      
      private
      
      # JavaScript字符串转义
      def escape_js(str)
        str.to_s.gsub(/['\\"]/) { |s| "\\#{s}" }
      end
      
      # 格式化时间
      def format_time(seconds)
        seconds = seconds.to_i
        if seconds < 60
          return "#{seconds}秒"
        elsif seconds < 3600
          minutes = seconds / 60
          seconds = seconds % 60
          return "#{minutes}分#{seconds}秒"
        else
          hours = seconds / 3600
          minutes = (seconds % 3600) / 60
          return "#{hours}时#{minutes}分"
        end
      end
    end
    
  end # module UIHelper
end # module HUB 